//
//  PPLoginViewController.m
//  PetParadise
//
//  Created by 陈无忌 on 8/1/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPLoginViewController.h"
#import "supportingHeadFiles.h"
#import "PPSystemConfiguraton.h"
#import "SBJson.h"
#import "PPApplyNotification.h"

@interface PPLoginViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *userNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextFiled;

@property (weak, nonatomic) PPSystemConfiguraton *config;

@end

@implementation PPLoginViewController
-(PPSystemConfiguraton *)config{
    if (!_config) {
        _config = [PPSystemConfiguraton sharedSystemConfiguration];
    }
    return _config;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.userNameTextField.delegate = self;
    self.passwordTextFiled.delegate = self;
    self.passwordTextFiled.secureTextEntry = YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - UITextField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([textField isEqual:self.userNameTextField]) {
        [self.userNameTextField resignFirstResponder];
    }
    if ([textField isEqual:self.passwordTextFiled
         ]) {
        [self.passwordTextFiled resignFirstResponder];
    }
    return YES;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if (![self.userNameTextField isExclusiveTouch]) {
        [self.userNameTextField resignFirstResponder];
    }
    if (![self.passwordTextFiled isExclusiveTouch]) {
        [self.passwordTextFiled resignFirstResponder];
    }
}

#pragma mark - Custom IBAction

//登录
- (IBAction)loginButton:(id)sender {
    //宠缘服务器同步登录
    [HUD showUIBlockingIndicatorWithText:@"正在登录"];
    //POST参数设置
    NSString *url = [PPAPIList getAPIList].PPLogin;
    NSString *userNameStr = self.userNameTextField.text;
    NSString *passWDStr = self.passwordTextFiled.text;
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:@{@"phoneNum":userNameStr,@"loginPassword":passWDStr}];
    if (self.config.pushId.length > 0 && self.config.pushId) {
        [params setObject:self.config.pushId forKey:@"pushKey"];
        [params setObject:@(4) forKey:@"deviceType"];
    }
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber *processResultNumber = responseObject[@"processResult"];
        if (processResultNumber.integerValue == 1) {
            //宠缘服务器登录成功
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSDictionary *userDic = resultMap[@"user"];
            NSArray *friendList = resultMap[@"userList"];
            NSArray *applyList = resultMap[@"applyList"];
            NSError *err = nil;
            if (applyList) {
                self.config.applyArray = [PPApplyNotification arrayOfModelsFromDictionaries:applyList error:&err];
            }
            
            if (friendList) {
                //好友列表获得
                self.config.friendArray = [PPUserInfo arrayOfModelsFromDictionaries:friendList error:&err];
            }

            //获取登录用户的信息
            self.config.userInfo = [[PPUserInfo alloc] initWithDictionary:userDic error:&err];
            //设置登录状态
            [self.config getUserSettingwithCompletion:nil];
            [self.config getConversationListwithComepletion:nil];
            [self.config getPetListwithComepletion:nil];
            [self.config getTopicListwithComepletion:nil];
            [self.config getCirclePushListwithCompletion:nil];
            
            self.config.isLogin = YES;
            //自动登录
            [[PPSystemConfiguraton sharedSystemConfiguration] saveLoginUserName:self.userNameTextField.text AndPassword:self.passwordTextFiled.text autoLogin:YES];
            //获取存在本地的通知
//            [[PPSystemConfiguraton sharedSystemConfiguration] getApplyfromLocal];
            //
            //环信登录
            [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:[NSString stringWithFormat:@"%d",self.config.userInfo.id] password:self.passwordTextFiled.text completion:^(NSDictionary *loginInfo, EMError *error) {
                if (loginInfo && !error) {
                    //环信服务器登陆成功
                    self.config.isEaseMobLogin = YES;
                    NSLog(@"环信登录成功");
                }else {
                    self.config.isEaseMobLogin = NO;
                }
                [HUD hideUIBlockingIndicator];
                //登录完成，返回
                [self dismissViewControllerAnimated:YES completion:nil];
            } onQueue:nil];
        }else{
            self.config.isLogin = NO;
            [self alertShow:responseObject[@"errorMsg"]];
            [HUD hideUIBlockingIndicator];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error){
        self.config.isLogin = NO;
        self.config.isEaseMobLogin = NO;
        [PPHUD hudShowWithString:@"网络不给力" andView:self.view];
        [HUD hideUIBlockingIndicator];
    }];
}

-(void)alertShow :(NSString *)string
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:string delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
